package com.qzsoft.zhjd.laboratory.modules.asphaltPenetrometer.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qzsoft.jeemis.common.exception.RenException;
import com.qzsoft.zhjd.common.components.BaseServiceComponent;
import com.qzsoft.zhjd.common.utils.AsphaltProtocolParserUtils;
import com.qzsoft.zhjd.common.utils.ParsedResult;
import com.qzsoft.zhjd.common.utils.ZhjdIotUtils;
import com.qzsoft.zhjd.laboratory.modules.asphaltPenetrometer.entity.AsphaltPenetrometerEntity;
import com.qzsoft.zhjd.laboratory.modules.asphaltPenetrometer.entity.AsphaltPenetrometerResEntity;
import com.qzsoft.zhjd.laboratory.modules.asphaltPenetrometer.entity.TaskEntity;
import com.qzsoft.zhjd.laboratory.modules.asphaltPenetrometer.mapper.AsphaltPenetrometerMapper;
import com.qzsoft.zhjd.laboratory.modules.asphaltPenetrometer.mapper.AsphaltPenetrometerResMapper;
import com.qzsoft.zhjd.laboratory.modules.asphaltPenetrometer.service.AsphaltPenetrometerResService;
import com.qzsoft.zhjd.laboratory.modules.asphaltPenetrometer.service.AsphaltPenetrometerService;
import com.qzsoft.zhjd.laboratory.modules.asphaltSofteningPoint.entity.AsphaltSofteningPointEntity;
import com.qzsoft.zhjd.laboratory.modules.asphaltSofteningPoint.entity.AsphaltSofteningPointResEntity;
import com.qzsoft.zhjd.laboratory.modules.asphaltSofteningPoint.mapper.AsphaltSofteningPointMapper;
import com.qzsoft.zhjd.laboratory.modules.asphaltSofteningPoint.mapper.AsphaltSofteningPointResMapper;
import com.qzsoft.zhjd.laboratory.modules.errorRecord.service.ErrorRecordService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;


@Service("asphaltPenetrometerService")
public class AsphaltPenetrometerServiceImpl extends ServiceImpl<AsphaltPenetrometerMapper, AsphaltPenetrometerEntity> implements AsphaltPenetrometerService {

    @Autowired
    private AsphaltPenetrometerMapper asphaltPenetrometerMapper;

    @Autowired
    private AsphaltPenetrometerResService asphaltPenetrometerResService;

    @Autowired
    private AsphaltPenetrometerResMapper resMapper;
    @Autowired
    private AsphaltSofteningPointResMapper softeningPointResMapper;

    @Autowired
    private AsphaltSofteningPointMapper softeningPointMapper;

    @Autowired
    private BaseServiceComponent baseServiceComponent;

    @Autowired
    private ErrorRecordService errorRecordService;

    private static Map<String, String> currentMap = new HashMap<>();
    //济微四标设备id；
    private static final String  DEVICE_ID = "0e3f15a2607fe3f60f76bd5594037b26";
    //试验类型，针入度
    private static final String  TYPE_ZRD = "ZRD";
    //试验类型，软化点
    private static final String  TYPE_RHD = "RHD";


    private static Logger log = LoggerFactory.getLogger(AsphaltPenetrometerServiceImpl.class);

    /**
     * 列表
     */
    @Override
    public IPage<JSONObject> queryPage(Map<String, Object> params) {
        IPage<AsphaltPenetrometerEntity> page = baseServiceComponent.getPage(params, AsphaltPenetrometerEntity.class);
        return asphaltPenetrometerMapper.queryPage(page, params);
    }

    /**
     * 信息
     *
     * @return AsphaltPenetrometerEntity
     */
    @Override
    public AsphaltPenetrometerEntity getInfo(String id) {
        return getById(id);
    }

    /**
     * 保存
     */
    @Override
    public void saveData(AsphaltPenetrometerEntity asphaltPenetrometer) {
        save(asphaltPenetrometer);
    }

    /**
     * 修改
     */
    @Override
    public void updateData(AsphaltPenetrometerEntity asphaltPenetrometer) {
        updateById(asphaltPenetrometer);
    }

    /**
     * 删除单条数据
     *
     * @param id
     */
    @Override
    public void deleteOneData(String id) {
        removeById(id);
    }




    /**
     * 删除
     */
    @Override
    public void deleteData(List<String> ids) {
        removeByIds(ids);
    }


    public void parsingData(String resData, String deviceId) {

        try {
            //处理多个“FAFBFC”数据；
            List<String> resDatas = transfer(resData);
            for(String res : resDatas){
                parseLabData(res,deviceId);
            }
        } catch (Exception e) {
            errorRecordService.saveErrorData(ZhjdIotUtils.ASPHALT_PENETROMETER,deviceId,resData);
            throw new RenException("数据解析异常");
        }

    }

    private List<String> transfer(String resData) {

        if(resData == null || !resData.contains("FAFBFC")){
            throw new RenException("马歇尔稳定度数据解析异常：" + resData);
        }
        //如果只有一个FAFBFC...数据，直接返回；
        if(resData.indexOf("FAFBFC") == resData.lastIndexOf("FAFBFC")){
            List<String> resDatas = new ArrayList<>();
            resDatas.add(resData);
            return resDatas;
        }
        //拼接第一个FAFBFC数据，有可能被截断，先查询上一条记录的原始数据，子表或主表
        //todo
        List<String> parts = new ArrayList<>();
        Pattern pattern = Pattern.compile("FAFBFC.*?(?=FAFBFC|$)", Pattern.DOTALL);
        Matcher matcher = pattern.matcher(resData);

        while (matcher.find()) {
            parts.add(matcher.group());
        }
        return parts;
    }

    /**
     * 解析沥青针入度仪数据三标，航天科宇设备v2.X
     * FAFBFC
     * 0B——数据字节数
     * A4——过程数据
     * 00——flag     0
     * 0080——实时位移，两位小数；    1.28mm;
     * 2134——实时温度，两位小数；   85.00℃
     * 0005——试验时间，单位100ms;  500ms;
     * 80——设备状态；    0
     * 00——针杆组件下落距离，单位mm;   0mm
     * FA——数据包校验和
     *
     * 四标蓝航中科
     * FAFBFC0703A702BB00FA5959
     *
     * FAFBFC
     * 0703
     * A7-结果数据
     * 02BB-位移6.99mm
     * 00FA-温度25.0℃
     * 59-sum
     *
     * FAFBFC0803A40102BB00FA58
     *
     * FAFBFC
     * 0803
     * A4——实时数据
     * 01——flag，试验数据；
     * 02BB——实时位移6.99mm
     * 00FA——实时温度25.0℃
     * 58——sum
     *
     *
     *
     *
     * @param resData  试验结果数据
     * @param deviceId 试验设备id
     */
    private void parseLabData(String resData, String deviceId) {
        Date nowDate = new Date();
        try {
            List<String> dataList = ZhjdIotUtils.analyzeExperimentalData(resData);
            //如果数据以00开头，可能设备刚开机或重启，表示一次新的实验开始
            if (StringUtils.equals(dataList.get(0), "00")) {
                currentMap.remove(deviceId);
            }
            //验证位不进行校验
            int i = 4;
            //如果是四标（蓝航中科），解码协议不一样；
            if(StrUtil.equals(DEVICE_ID,deviceId)){
                i = 5;
            }
            //试验数据
            if (StringUtils.equals(ZhjdIotUtils.DATA_TYPE_TEST, dataList.get(i))) {
                AsphaltPenetrometerEntity entity = new AsphaltPenetrometerEntity();
                entity.setDeviceId(deviceId);
                if (currentMap.get(deviceId) == null) {
                    AsphaltPenetrometerResEntity resEntity = new AsphaltPenetrometerResEntity();
                    resEntity.setDeviceId(deviceId);
                    asphaltPenetrometerResService.save(resEntity);
                    currentMap.put(deviceId, resEntity.getId());
                }
                //设置实验结果数据id
                entity.setResId(currentMap.get(deviceId));

                entity.setOriginalData(resData);
                entity.setCreateTime(nowDate);
                i++;
                entity.setFlag(dataList.get(i));

                // 将16进制转换为10进制数据，不含（0x）
                // 实时位移
                i++;
                entity.setRealTimeDisplacement(ZhjdIotUtils.hexToTwoPoint(dataList.get(i)+dataList.get(i + 1)));
                // 实时温度
                i += 2;
                //如果是四标的；
                if(StrUtil.equals(DEVICE_ID,deviceId)){
                    entity.setRealTimeTemperature(ZhjdIotUtils.hexToOnePoint(dataList.get(i) + dataList.get(i + 1)));
                } else {
                    entity.setRealTimeTemperature(ZhjdIotUtils.hexToTwoPoint(dataList.get(i) + dataList.get(i + 1)));
                    //试验时间
                    i+=2;
                    entity.setTestTime(Integer.parseInt(dataList.get(i) + dataList.get(i+1),16));
                    //设备状态
                    i+=2;
                    entity.setStatus(dataList.get(i));
                    //针杆组件下落距离
                    i++;
                    entity.setPo(Integer.parseInt(dataList.get(i),16));
                }
                save(entity);
                //结果数据
            } else if (StringUtils.equals(ZhjdIotUtils.DATA_TYPE_RES, dataList.get(i))) {
                AsphaltPenetrometerResEntity resEntity = new AsphaltPenetrometerResEntity();
                resEntity.setId(currentMap.get(deviceId));
                currentMap.remove(deviceId);
                resEntity.setDeviceId(deviceId);
                resEntity.setOriginalData(resData);
                resEntity.setCreateTime(nowDate);

                // 将16进制转换为10进制数据，不含（0x）
                // 实时位移
                i++;
                resEntity.setRealTimeDisplacement(ZhjdIotUtils.hexToTwoPoint(dataList.get(i)+dataList.get(i + 1)));
                //如果是四标的
                if(StrUtil.equals(deviceId,DEVICE_ID)) {
                    // 实时温度
                    i += 2;
                    resEntity.setRealTimeTemperature(ZhjdIotUtils.hexToOnePoint(dataList.get(i)+dataList.get(i + 1)));
                }
//                // 实时温度
//                i += 2;
//                resEntity.setRealTimeTemperature(ZhjdIotUtils.hexToDecimalism(dataList.get(i), dataList.get(i + 1)));

                asphaltPenetrometerResService.saveOrUpdate(resEntity);
            } else {
                throw new RenException("针入度数据解析异常：" + resData);
            }
        } catch (Exception e) {
            errorRecordService.saveErrorData(ZhjdIotUtils.ASPHALT_PENETROMETER, deviceId, resData);
            throw new RenException("数据解析异常");
        }
    }


    /**
     * 解析济微二标沥青针入度仪数据， 小数点两位；当实验完成标志=1时，代表有效数据，其他为无效数据；
     *01031E 0002 0000 0006 069C 01F4 0005 007A 0000 0557 08E5 058A 0697 0001 0002 0032 3E2E
     * @param resData  试验结果数据
     * @param deviceId 试验设备id
     *        以试验完成作为区分两条不同试验的标志；
     */
    @Override
    public void parsingDataTwob(String resData, String deviceId) {
        Date nowDate = new Date();
        try {
            //结果数据
            AsphaltPenetrometerResEntity resEntity = new AsphaltPenetrometerResEntity();
            //过程数据；
            AsphaltPenetrometerEntity entity = new AsphaltPenetrometerEntity();
            List<String> dataList = ZhjdIotUtils.stringToList(resData);
            if(currentMap.get(deviceId) == null){
                resEntity.setDeviceId(deviceId);
                asphaltPenetrometerResService.save(resEntity);
                currentMap.put(deviceId,resEntity.getId());
            }
            //验证位不进行校验
            int i = 3;
            //设备代号；
            resEntity.setDeviceNo(getValue(dataList,i));
            i+=2;
            //试验状态
            resEntity.setTestStatus(getValue(dataList,i));
            i+=2;
            //试验编号
            resEntity.setTestNo(getValue(dataList,i));
            i+=2;
            //水域温度；
            String tem = ZhjdIotUtils.hexToString(dataList.get(i) + dataList.get(i + 1));
            resEntity.setWaterBathTemperature(tem);
            entity.setRealTimeTemperature(new BigDecimal(tem));
            i+=2;
            //设定温度；
            resEntity.setSettingTemperature(ZhjdIotUtils.hexToString(dataList.get(i)+dataList.get(i + 1)));
            i+=2;
            //下落时间；
            resEntity.setFallingTime(getValue(dataList,i));
            i+=2;
            //绝对位置；
            resEntity.setAbsolutePosition(ZhjdIotUtils.hexToString(dataList.get(i)+dataList.get(i+1)));
            i+=2;
            //相对位置
            String position = ZhjdIotUtils.hexToString(dataList.get(i) + dataList.get(i + 1));
            resEntity.setRelativePosition(position);
            entity.setRealTimeDisplacement(new BigDecimal(position));
            i+=2;
            //针入度1
            resEntity.setZrdValue1(new BigDecimal(ZhjdIotUtils.hexToString(dataList.get(i)+dataList.get(i+1))));
            i+=2;
            //针入度2
            resEntity.setZrdValue2(new BigDecimal(ZhjdIotUtils.hexToString(dataList.get(i)+dataList.get(i+1))));
            i+=2;
            //针入度3
            resEntity.setZrdValue3(new BigDecimal(ZhjdIotUtils.hexToString(dataList.get(i)+dataList.get(i+1))));
            i+=2;
            //针入度平均
            resEntity.setZrdAvg(new BigDecimal(ZhjdIotUtils.hexToString(dataList.get(i)+dataList.get(i+1))));
            i+=2;
            //判断是结果数据还是过程数据；
            //试验完成标志 = 1 结果数据；=0 过程数据；
            //试验完成标志（0未完成 1完成）
            String completion = getValue(dataList, i);
            if("1".equals(completion)){
                resEntity.setTestCompletionMark(completion);
                i+=2;
                //当前界面号
                resEntity.setCurrentPageNo(getValue(dataList,i));
                i+=2;
                //试验倒计时；
                resEntity.setTestCountdown(getValue(dataList,i));
                i+=2;
                //crc检验低 crc检验高
                resEntity.setTestingHigh(String.valueOf(Integer.parseInt(resData.substring(resData.length()-4), 16)));
                resEntity.setOriginalData(resData);
                resEntity.setCreateTime(nowDate);
                currentMap.remove(deviceId);
                asphaltPenetrometerResService.saveOrUpdate(resEntity);
            } else {
                entity.setResId(currentMap.get(deviceId));
                entity.setDeviceId(deviceId);
                entity.setOriginalData(resData);
                entity.setCreateTime(nowDate);
                save(entity);
            }
        } catch (Exception e) {
            errorRecordService.saveErrorData(ZhjdIotUtils.ASPHALT_PENETROMETER, deviceId, resData);
            throw new RenException("数据解析异常");
        }
    }

    /**
     * 重新解析航天科宇沥青针入度原始数据；v2.X版本；
     * 1、解析结果数据
     * 2、解析过程数据；
     * @param deviceId
     */
    @Override
    public void reParsingData(String deviceId) {
        //1、解析结果数据
        if(StringUtils.isBlank(deviceId)){
            return;
        }
        LambdaQueryWrapper<AsphaltPenetrometerResEntity> wrappers = new LambdaQueryWrapper<>();
        wrappers.eq(AsphaltPenetrometerResEntity::getDeviceId,deviceId);
//        wrappers.eq(AsphaltPenetrometerResEntity::getFlag,"01");
//        wrappers.isNotNull(AsphaltPenetrometerResEntity::getOriginalData);
        List<AsphaltPenetrometerResEntity> resEntities = resMapper.selectList(wrappers);
//        if(CollUtil.isEmpty(resEntities)){
//            return;
//        }
//        for(AsphaltPenetrometerResEntity resEntity:resEntities) {
//            String originalData = resEntity.getOriginalData();
//            List<String> dataList = ZhjdIotUtils.analyzeExperimentalData(originalData);
//            int i = 5;
//            resEntity.setRealTimeDisplacement(ZhjdIotUtils.hexToTwoPoint(dataList.get(i) + dataList.get(i + 1)));
//            resMapper.updateById(resEntity);
//        }
        //2、解析过程数据；
        Set<String> resIds = resEntities.stream().map(AsphaltPenetrometerResEntity::getId).collect(Collectors.toSet());
        //根据结果id查询过程数据；
        List<AsphaltPenetrometerEntity> entities = baseMapper.selectList(new LambdaQueryWrapper<AsphaltPenetrometerEntity>()
                .in(AsphaltPenetrometerEntity::getResId, resIds)
                .isNotNull(AsphaltPenetrometerEntity::getOriginalData));
//                .eq(AsphaltPenetrometerEntity::getFlag,"01"));
        if(CollUtil.isEmpty(entities)){
            return;
        }
        for(AsphaltPenetrometerEntity entity:entities){
            String originalData = entity.getOriginalData();
            if(StringUtils.isNotBlank(originalData)){
                List<String> dataList = ZhjdIotUtils.analyzeExperimentalData(originalData);
                int i = 5;
                entity.setFlag(dataList.get(i));
                i++;
                entity.setRealTimeDisplacement(ZhjdIotUtils.hexToTwoPoint(dataList.get(i)+dataList.get(i + 1)));
                // 实时温度
                i += 2;
                entity.setRealTimeTemperature(ZhjdIotUtils.hexToTwoPoint(dataList.get(i) + dataList.get(i + 1)));
                //试验时间
                i+=2;
                entity.setTestTime(Integer.parseInt(dataList.get(i) + dataList.get(i+1),16));
                //设备状态
                i+=2;
                entity.setStatus(dataList.get(i));
                //针杆组件下落距离
                i++;
                entity.setPo(Integer.parseInt(dataList.get(i),16));
                baseMapper.updateById(entity);
            }
        }
    }


    @Override
    public String parsingDataOneb(JSONObject json) {
        try {
            //结果数据
            AsphaltPenetrometerResEntity resEntity = new AsphaltPenetrometerResEntity();

            String stationCode = json.getString("stationCode");
            resEntity.setDeviceId(stationCode);
            resEntity.setDeviceNo(json.getString("sbbh"));
            resEntity.setOriginalData(json.toJSONString());
            resEntity.setZrdValue1(isBigDecimal(json.getString("zrdvalue1")));
            resEntity.setZrdValue2(isBigDecimal(json.getString("zrdvalue2")));
            resEntity.setZrdValue3(isBigDecimal(json.getString("zrdvalue3")));
            resEntity.setZrdAvg(isBigDecimal(json.getString("zrdavg")));
            resEntity.setCreateTime(new Date());
            //插入结果数据；
            asphaltPenetrometerResService.save(resEntity);
            String resId = resEntity.getId();

            //针入度试验1的过程数据对.(贯入量(mm),时间(0.1s) 做多60秒钟，共120个数据，每组数据用“；”隔开。例如：2.345,1.4；2.556,1.8；2.876,2.4； )
            String zrd1process = json.getString("zrd1process");
            String zrd2process = json.getString("zrd2process");
            String zrd3process = json.getString("zrd3process");
            if (StrUtil.isNotBlank(zrd1process)) {
                saveProcessData(zrd1process, resId, stationCode, 1);
            }
            if (StrUtil.isNotBlank(zrd2process)) {
                saveProcessData(zrd2process, resId, stationCode, 2);
            }
            if (StrUtil.isNotBlank(zrd3process)) {
                saveProcessData(zrd3process, resId, stationCode, 3);
            }
            return json.getString("syjid");
        } catch (Exception e) {
            errorRecordService.saveErrorData(ZhjdIotUtils.ASPHALT_PENETROMETER, "1111", json.toJSONString());
            throw new RenException("数据解析异常");
        }

    }

    /**
     * 生成一条试验数据；返回给试验仪器；
     */
    @Override
    public TaskEntity getTaskCode(String deviceNo) {
        AsphaltPenetrometerResEntity resEntity = new AsphaltPenetrometerResEntity();
        resEntity.setDeviceId(deviceNo);
        asphaltPenetrometerResService.save(resEntity);
        TaskEntity entity = new TaskEntity();
        entity.setTaskId(resEntity.getId());
        return entity;
    }

    /**
     * 接收申克路业仪器有限公司的数据；针入度、软化点；
     * type标识：
     * 针入度：ZRD,
     * 软化点：RHD
     * @param json
     */
    @Override
    public void dataEntry(JSONObject json) {
        //结果数据
        AsphaltPenetrometerResEntity resEntity = new AsphaltPenetrometerResEntity();
        String type = json.getString("type");
        String deviceId = json.getString("deviceId");
        if(StrUtil.isBlank(deviceId)){
            throw new RuntimeException();
        }
        String data = json.getString("data");

        if(StrUtil.isNotBlank(data)) {
            Date date = new Date();
            if (TYPE_ZRD.equals(type)) {
                //插入针入度数据
                AsphaltPenetrometerResEntity entity = json.getObject("data",AsphaltPenetrometerResEntity.class);
                //绑定项目标段；
                entity.setCreateTime(date);
                entity.setDeviceId(deviceId);
                entity.setOriginalData(json.toJSONString());
                asphaltPenetrometerResService.save(entity);

                resEntity.setCreateTime(new Date());
                //插入结果数据；
                asphaltPenetrometerResService.save(resEntity);
            } else if (TYPE_RHD.equals(type)) {
                //插入软化点数据；
                AsphaltSofteningPointResEntity entity = json.getObject("data",AsphaltSofteningPointResEntity.class);
                //绑定项目标段；
                entity.setDeviceId(deviceId);
                entity.setCreateTime(date);
                entity.setOriginalData(json.toJSONString());
                softeningPointResMapper.insert(entity);
            } else {
                errorRecordService.saveErrorData(ZhjdIotUtils.ASPHALT_PENETROMETER, deviceId, json.toJSONString());
                throw new RuntimeException();
            }
        } else {
            errorRecordService.saveErrorData(ZhjdIotUtils.ASPHALT_PENETROMETER, deviceId, json.toJSONString());
            throw new RuntimeException();
        }

    }

    /**
     * //解析过程数据
     * 贯入量mm，时间0.1s
     * 0.0,0.0;
     * 7.9,0.5;
     * 15.7,1.0;
     * 23.2,1.5;
     * 30.2,2.0;
     * 36.5,2.5;
     * 42.0,3.0;
     * 46.7,3.5;
     * 50.3,4.0;
     * 52.8,4.5;
     * 54.2,5.0;
     * 0.0,0.0;
     */
    private void saveProcessData(String process,String resId,String deviceId,int num) {
        //            解析过程数据
        String[] split = process.split(";");
        if (split.length > 0) {
            Date date = new Date();
            List<AsphaltPenetrometerEntity> entities = new ArrayList<>();
            for (int i = 0; i < split.length; i++) {
                AsphaltPenetrometerEntity entity = new AsphaltPenetrometerEntity();
                entity.setResId(resId);
                entity.setDeviceId(deviceId);
                entity.setCreateTime(date);
                if(StrUtil.isNotBlank(split[i])) {
                    String[] split1 = split[i].split(",");
                    if (split1.length != 2) {
                        continue;
                    }
                    entity.setGcValue(num);
                    entity.setGuanrl(split1[0]);
                    entity.setTestTime(Integer.valueOf(split1[1]));
                }
                entities.add(entity);
            }
            saveBatch(entities);
        }
    }


    private String getValue(List<String> dataList,int i) {
        return String.valueOf(Integer.parseInt(dataList.get(i)+dataList.get(i + 1), 16));
    }

    private BigDecimal isBigDecimal(String str) {
        if(str == null || str.equals("")) {
            return null;
        }
        str = str.trim();
        if(str.matches("^[0-9]+.?[0-9]*$")) {
            return new BigDecimal(str);
        }else{
            return null;
        }
    }
    /**
     * 绑定材料
     *
     * @param asphaltPenetrometerResEntity
     */
    public void changeSample(AsphaltPenetrometerResEntity asphaltPenetrometerResEntity) {
        //更新试验结果表
        asphaltPenetrometerResService.updateById(asphaltPenetrometerResEntity);
        //查询试验过程数据
        List<AsphaltPenetrometerEntity> processList = list(new LambdaQueryWrapper<AsphaltPenetrometerEntity>().eq(AsphaltPenetrometerEntity::getResId, asphaltPenetrometerResEntity.getId()));
        if (CollectionUtil.isNotEmpty(processList)) {
            for (AsphaltPenetrometerEntity item : processList) {
                item.setSampleId(asphaltPenetrometerResEntity.getSampleId());
            }
            updateBatchById(processList);
        }
    }

    @Override
    public String parsingDataDTU(String deviceId, String json) {
        if (StringUtils.isEmpty(deviceId) || StringUtils.isEmpty(json)) {
            errorRecordService.saveErrorData(ZhjdIotUtils.ASPHALT_PENETROMETER, "1111", json);
            throw new RenException("数据解析异常");
        }
        try {
            //结果数据
            AsphaltPenetrometerResEntity resEntity = new AsphaltPenetrometerResEntity();
            resEntity.setOriginalData(json);

            String[] data = json.split(" ");
            String hex = "";
            int s = 0;
            for (int i = 4; i < data.length; i++) {
                String item = data[i];
                Integer value = null;
                if (i % 2 == 0) {
                    hex = item;
                } else {
                    hex += item;
                    s++;
                    value = Integer.parseInt(hex, 16);
                }
                if (value == null) continue;
                switch(s) {
                    case 1:
                        resEntity.setDeviceNo(value+"");
                        break;
                    case 2:
                        // 处理s=2的情况
                        break;
                    case 3:
                        if (value > 100) {
                            resEntity.setRealTimeTemperature(new BigDecimal(value).divide(new BigDecimal("10"), 1, RoundingMode.HALF_UP));
                        } else {
                            resEntity.setRealTimeTemperature(new BigDecimal(value));
                        }
                        break;
                    case 4:
                        if (value > 1000) {
                            resEntity.setZrdValue1(new BigDecimal(value).divide(new BigDecimal("10"), 1, RoundingMode.HALF_UP));
                        } else {
                            resEntity.setZrdValue1(new BigDecimal(value));
                        }
                        break;
                    case 5:
                        if (value > 1000) {
                            resEntity.setZrdValue2(new BigDecimal(value).divide(new BigDecimal("10"), 1, RoundingMode.HALF_UP));
                        } else {
                            resEntity.setZrdValue2(new BigDecimal(value));
                        }
                        break;
                    case 6:
                        if (value > 1000) {
                            resEntity.setZrdValue3(new BigDecimal(value).divide(new BigDecimal("10"), 1, RoundingMode.HALF_UP));
                        } else {
                            resEntity.setZrdValue3(new BigDecimal(value));
                        }
                        break;
                    case 7:
                        resEntity.setZrdAvg(new BigDecimal(value));
                        break;
                }
            }

            resEntity.setDeviceId(deviceId);
            resEntity.setCreateTime(new Date());
            //插入结果数据；
            asphaltPenetrometerResService.save(resEntity);
            String resId = resEntity.getId();

            return resId;
        } catch (Exception e) {
            errorRecordService.saveErrorData(ZhjdIotUtils.ASPHALT_PENETROMETER, "1111", json);
            throw new RenException("数据解析异常");
        }

    }

    /**
     * 沥青软化点仪 -- 北京中科建仪电子科技有限公司
     * @param resData
     * @param deviceId
     */
    @Override
    @Transactional
    public void parsingDataSoftPointerOfBjzkjydz(String resData, String deviceId) {
        System.out.println("北京中科建仪电子科技有限公司沥青软化点仪resData------->>>>>>"+resData);
        System.out.println("deviceId------->>>>>>"+deviceId);
        String deviceType = "SOFTENING_POINT_BJZKJYDZ";
        if(StringUtils.isNotBlank(deviceId)){
            ParsedResult parsedResult = AsphaltProtocolParserUtils.parseHexString(resData, deviceType);
            System.out.println("parsedResult------->>>>>>" + JSON.toJSONString(parsedResult));
            if(parsedResult != null){
                //试验数据
                System.out.println("parsedResult.getDataType()------->>>>>>" + parsedResult.getDataType());
                if(parsedResult.getDataType() == AsphaltProtocolParserUtils.TYPE_REALTIME){
                    AsphaltSofteningPointEntity entity = new AsphaltSofteningPointEntity();
                    entity.setDeviceId(deviceId);
                    entity.setOriginalData(resData);
                    entity.setMin(parsedResult.getMin().intValue());
                    entity.setSecond(parsedResult.getSec().intValue());
                    entity.setNum1(parsedResult.getNum1().intValue());
                    entity.setNum2(parsedResult.getNum2().intValue());
                    entity.setTemp1(parsedResult.getDt1().divide(new BigDecimal(10)));
                    entity.setTemp2(parsedResult.getDt2().divide(new BigDecimal(10)));
                    entity.setCreateTime(new Date());
                    if(parsedResult.getFlag() >= 0){
                        entity.setFlag(parsedResult.getFlag() == 1 ? "01" : "00");
                    }
                    System.out.println("AsphaltSofteningPointEntity------->>>>>>" + JSON.toJSONString(entity));
                    softeningPointMapper.insert(entity);
                }else if(parsedResult.getDataType() == AsphaltProtocolParserUtils.TYPE_RESULT){
                    AsphaltSofteningPointResEntity entity = new AsphaltSofteningPointResEntity();
                    entity.setDeviceId(deviceId);
                    entity.setOriginalData(resData);
                    entity.setMin(parsedResult.getMin().intValue());
                    entity.setSecond(parsedResult.getSec().intValue());
                    entity.setNum1(parsedResult.getNum1().intValue());
                    entity.setNum2(parsedResult.getNum2().intValue());
                    entity.setTemp1(parsedResult.getDt1().divide(new BigDecimal(10)));
                    entity.setTemp2(parsedResult.getDt2().divide(new BigDecimal(10)));
                    entity.setCreateTime(new Date());
                    if(parsedResult.getFlag() >= 0){
                        entity.setFlag(parsedResult.getFlag() == 1 ? "01" : "00");
                    }
                    System.out.println("AsphaltSofteningPointEntity------->>>>>>" + JSON.toJSONString(entity));
                    softeningPointResMapper.insert(entity);
                    LambdaUpdateWrapper<AsphaltSofteningPointEntity> asphaltPenetrometerEntityLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                    asphaltPenetrometerEntityLambdaUpdateWrapper.eq(AsphaltSofteningPointEntity::getDeviceId, deviceId);
                    asphaltPenetrometerEntityLambdaUpdateWrapper.set(AsphaltSofteningPointEntity::getResId, entity.getId());
                    softeningPointMapper.update(null,asphaltPenetrometerEntityLambdaUpdateWrapper);
                }
            }
        }
    }


    /**
     * 针入度 -- 北京中科建仪电子科技有限公司
     * @param resData
     * @param deviceId
     */
    @Override
    public void parsingDataOfBjzkjydz(String resData, String deviceId) {
        System.out.println("北京中科建仪电子科技有限公司针入度resData------->>>>>>"+resData);
        System.out.println("deviceId------->>>>>>"+deviceId);
        String deviceType = "PENETRATION_BJZKJYDZ";
        if(StringUtils.isNotBlank(deviceId)){
            ParsedResult parsedResult = AsphaltProtocolParserUtils.parseHexString(resData, deviceType);
            System.out.println("parsedResult------->>>>>>" + JSON.toJSONString(parsedResult));
            if(parsedResult != null){
                //试验数据
                System.out.println("parsedResult.getDataType()------->>>>>>" + parsedResult.getDataType());
                if(parsedResult.getDataType() == AsphaltProtocolParserUtils.TYPE_REALTIME){
                    AsphaltPenetrometerEntity entity = new AsphaltPenetrometerEntity();
                    entity.setDeviceId(deviceId);
                    entity.setOriginalData(resData);
                    entity.setRealTimeDisplacement(parsedResult.getDpOrDs().divide(new BigDecimal(100)));
                    entity.setRealTimeTemperature(parsedResult.getDtOrDf().divide(new BigDecimal(10)));
                    entity.setCreateTime(new Date());
                    if(parsedResult.getFlag() >= 0){
                        entity.setFlag(parsedResult.getFlag() == 1 ? "01" : "00");
                    }
                    System.out.println("AsphaltPenetrometerEntity------->>>>>>" + JSON.toJSONString(entity));
                    asphaltPenetrometerMapper.insert(entity);
                }else if(parsedResult.getDataType() == AsphaltProtocolParserUtils.TYPE_RESULT){
                    //结果数据
                    AsphaltPenetrometerResEntity entity = new AsphaltPenetrometerResEntity();
                    entity.setDeviceId(deviceId);
                    entity.setOriginalData(resData);
                    entity.setRealTimeDisplacement(parsedResult.getDpOrDs().divide(new BigDecimal(100)));
                    entity.setRealTimeTemperature(parsedResult.getDtOrDf().divide(new BigDecimal(10)));
                    entity.setCreateTime(new Date());
                    System.out.println("AsphaltPenetrometerResEntity------->>>>>>" + JSON.toJSONString(entity));
                    resMapper.insert(entity);
                    LambdaUpdateWrapper<AsphaltPenetrometerEntity> asphaltPenetrometerEntityLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                    asphaltPenetrometerEntityLambdaUpdateWrapper.eq(AsphaltPenetrometerEntity::getDeviceId, deviceId);
                    asphaltPenetrometerEntityLambdaUpdateWrapper.set(AsphaltPenetrometerEntity::getResId, entity.getId());
                    asphaltPenetrometerMapper.update(null,asphaltPenetrometerEntityLambdaUpdateWrapper);
                }
            }
        }
    }
}
